package com.zzusedating.androidapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.zzusedating.androidapp.customlayout.TextViewWithClearButton;
import com.zzusedating.androidapp.tools.MyApplication;
import com.zzusedating.androidapp.tools.ConstantsTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


public class RegisterActivity extends BaseActivity {
    private static final String TAG = "RegisterActivity";
    private String LAST_EMAIL = "";
    private final String VERIFY_CODE_SENT_ = "验证码已发送";
    private final String EMAIL_REGISTERED_ = "邮箱已被注册";
    private final String EMAIL_FORMAT_ = "邮箱格式不正确";
    private final String VERIFY_ERROR_ = "验证码错误";

    private final int VERIFY_CODE_SENT_I = 101;
    private final int EMAIL_REGISTERED_I = 103;
    private final int EMAIL_FORMAT_ERROR_I = 104;
    private final int VERIFY_ERROR_I = 105;
    private final int REG_NEXT_SUCCESS_I = 106;

    private View.OnClickListener verifyListener;
    private View.OnClickListener nextListener;

    private Callback verifyCallback;
    private Callback nextCallback;

    private Button nextButton;
    private Handler handler;
    private TextViewWithClearButton emailView;
    private TextViewWithClearButton verifyView;
    private TextViewWithClearButton passwordView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_layout);

        initListener();
        initCallback();

        emailView = findViewById(R.id.Register_EmailCustomTVWCBView);
        verifyView = findViewById(R.id.Register_VerificationCustomTVWCBView);
        passwordView = findViewById(R.id.Register_PasswordTVWCBView);
        nextButton = findViewById(R.id.Register_NextButton);

        verifyView.setOnClickListenerToVerifyCode(verifyListener);
        nextButton.setOnClickListener(nextListener);

    }

    /**
     * 初始化监听器
     */
    protected void initListener(){
        verifyListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(emailView.getText())){
                    Toast.makeText(RegisterActivity.this, "请输入邮箱地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                LAST_EMAIL = emailView.getText();

                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.VERIFY_CODE_URL, emailView.getText(), "register"))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(verifyCallback);
            }
        };

        nextListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(emailView.getText())){
                    Toast.makeText(RegisterActivity.this, "请输入邮箱地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(verifyView.getText())){
                    Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(passwordView.getText())){
                    Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.isEmpty(LAST_EMAIL) && !TextUtils.equals(LAST_EMAIL, emailView.getText())){
                    Toast.makeText(RegisterActivity.this, "邮箱已更改，请重新发送验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.REG_NEXT, verifyView.getText(), passwordView.getText()))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(nextCallback);
            }
        };
    }

    /**
     * 回调接口初始化
     */
    protected void initCallback(){

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case VERIFY_CODE_SENT_I:
                        Toast.makeText(RegisterActivity.this, VERIFY_CODE_SENT_, Toast.LENGTH_SHORT).show();
                        break;
                    case EMAIL_FORMAT_ERROR_I:
                        Toast.makeText(RegisterActivity.this, EMAIL_FORMAT_, Toast.LENGTH_SHORT).show();
                        break;
                    case EMAIL_REGISTERED_I:
                        Toast.makeText(RegisterActivity.this, EMAIL_REGISTERED_, Toast.LENGTH_SHORT).show();
                        break;
                    case ConstantsTools.NETWORK_ERROR_I:
                        Toast.makeText(RegisterActivity.this, ConstantsTools.NETWORK_ERROR_, Toast.LENGTH_SHORT).show();
                        break;
                    case VERIFY_ERROR_I:
                        Toast.makeText(RegisterActivity.this, VERIFY_ERROR_, Toast.LENGTH_SHORT).show();
                        break;
                    case REG_NEXT_SUCCESS_I:
                        startActivity(new Intent(RegisterActivity.this, RegBasicProfileActivity.class));
                        break;
                }
                return true;
            }
        });

        verifyCallback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: response code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject;
                    if (response.body() != null){
                        jsonObject = new JSONObject(response.body().string());
                        if (jsonObject.getInt("status") == 1){
                            handler.sendMessage(ConstantsTools.createMessage(VERIFY_CODE_SENT_I));
                        }
                        else {
                            int code = jsonObject.getInt("code");
                            switch (code){
                                case 2:
                                    handler.sendMessage(ConstantsTools.createMessage(EMAIL_FORMAT_ERROR_I));
                                    break;
                                case 3:
                                    handler.sendMessage(ConstantsTools.createMessage(EMAIL_REGISTERED_I));
                                    break;
                                default:
                                    handler.sendMessage(ConstantsTools.createMessage());
                                    break;
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        nextCallback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(RegisterActivity.this, ConstantsTools.NETWORK_ERROR_, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: response code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        handler.sendMessage(ConstantsTools.createMessage(REG_NEXT_SUCCESS_I));
                    }
                    else {
                        if (jsonObject.getInt("code") == 3)
                            handler.sendMessage(ConstantsTools.createMessage(VERIFY_ERROR_I));
                        else
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
